//
//  CreatWalletViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2018/12/26.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "CreatWalletViewController.h"
#import "WallectService.h"
#import "CreateSuccessViewController.h"
#import "RegistrationCodeView.h"
#import "WebInfoViewController.h"
@interface CreatWalletViewController ()<UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UITextField *accountTF;
@property (nonatomic,strong) UITextField *psw1;
@property (nonatomic,strong) UITextField *psw2;
@property (nonatomic,strong) UITextField *pswTip;
@property (nonatomic,strong) UITextField *pinvitationTF;
@property (nonatomic,strong) WallectService *wallectService;
@property (nonatomic,weak) XThemeFlatButton *improtBtn;
@property (nonatomic,assign) BOOL agree;

@end

@implementation CreatWalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self action];
}

- (void)action{
    [self importBtnEnable];
    kWeakSelf(self);
    [self.improtBtn addTapBlock:^(UIButton * _Nonnull btn) {
       
        if (!weakself.accountTF.text.length) {
            [weakself.view makeToast:XLocalized(@"EOS钱包名称")];
            return;
        }
        if (![RegularExp validateEosAccountName:weakself.accountTF.text] && weakself.accountTF.text.length != 12) {
            [weakself.view makeToast:weakself.accountTF.placeholder];
            return;
        }
        
        if (weakself.psw1.text.length < 8) {
            [weakself.view makeToast:XLocalized(@"密码最小长度为8位!")];
            return;
        }
        if (![weakself.psw1.text isEqualToString:weakself.psw2.text]) {
            [weakself.view makeToast:XLocalized(@"密码不一致!")];
            return;
        }
        if (!weakself.pinvitationTF.text.length ) {
            [weakself.view makeToast:XLocalized(@"请输入注册码")];
            return;
        }
        weakself.wallectService.accountName = weakself.accountTF.text;
        weakself.wallectService.pswTip = weakself.pswTip.text;
        weakself.wallectService.psw = weakself.psw1.text;
        
        ///单私钥
        weakself.wallectService.ownerPrivateKey = [[EosPrivateKey alloc]initEosPrivateKey];
        weakself.wallectService.activePrivateKey =  weakself.wallectService.ownerPrivateKey;
        ///双私钥
//        weakself.wallectService.activePrivateKey = [[EosPrivateKey alloc]initEosPrivateKey];
         NSLog(@"ownerPrivateKey:\n %@ \n ownerPublicKey:\n %@\n activePrivateKey:\n%@\n activePublicKey:\n %@\n", weakself.wallectService.ownerPrivateKey.eosPrivateKey , weakself.wallectService.ownerPrivateKey.eosPublicKey , weakself.wallectService.activePrivateKey.eosPrivateKey, weakself.wallectService.activePrivateKey.eosPublicKey);
        weakself.wallectService.invite_code = weakself.pinvitationTF.text;
        [XAlertTool alertTitle:@"请知悉" message:@"· 创建账号名所需的 EOS 由 BEES 代为支付  \n· 账号所有权/使用权归用户所有，创建账号后的所有操作与 BEES 无关" cancelAction:^{
        } sureAction:^{
            [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
            [weakself.wallectService creatAccoutComplete:^(BOOL result, NSString * _Nonnull errorMsg) {
                [MBProgressHUD hideHUDForView:weakself.view];
                if (result) {
                    [weakself.view makeToast:XLocalized(@"创建成功")];
                    CreateSuccessViewController *success = [CreateSuccessViewController new];
                    success.wallectService = weakself.wallectService;
                    [weakself.navigationController pushViewController:success animated:YES];
                }else{
                    [weakself.view makeToast:errorMsg];
                }
            }];
        }];
    }];
}

- (void)setupUI{
    self.title = XLocalized(@"创建钱包");
    UILabel *tipLab = [UILabel new];
    tipLab.font = kBoldFont(16);
    tipLab.textColor = UIColorHex(333333);
    tipLab.text = XLocalized(@"请设定账号名");
    [self.contentView addSubview:tipLab];
    [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(kNormalSpace);
    }];
    self.accountTF = [UITextField new];
    [self.accountTF setValue:@12 forKey:Limit_NAME];
    self.accountTF.layer.cornerRadius = AdaptedWidth(10);
    self.accountTF.font = kDefaultFont(14);
    self.accountTF.backgroundColor = UIColorHex(#F7F7F7);
    self.accountTF.placeholder = XLocalized(@"12位字符，由a~z和1~5以及符号.组成。");
    self.accountTF.leftViewMode = UITextFieldViewModeAlways;
    UIView*letfV0 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.accountTF.leftView = letfV0;
    [self.contentView addSubview:self.accountTF];
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
        make.top.equalTo(tipLab.mas_bottom).offset(AdaptedWidth(15));
    }];
    UILabel *tipLab2 = [UILabel new];
    tipLab2.font = kBoldFont(16);
    tipLab2.textColor = UIColorHex(333333);
    tipLab2.text =  XLocalized(@"设定密码(不少于8位)");
    [self.contentView addSubview:tipLab2];
    [tipLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.accountTF.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    self.psw1 = [UITextField new];
    self.psw1.secureTextEntry = YES;
    self.psw1.borderStyle = UITextBorderStyleNone;
    self.psw1.layer.cornerRadius = AdaptedWidth(10);
    self.psw1.backgroundColor = UIColorHex(#F7F7F7);
    self.psw1.placeholder = XLocalized(@"请输入您的密码");;
    self.psw1.font = kDefaultFont(14);
    self.psw1.delegate = self;
    UIView*letfV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.psw1.leftView = letfV;
    self.psw1.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.psw1];
    [self.psw1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLab2.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    self.psw2 = [UITextField new];
    self.psw2.secureTextEntry = YES;
    self.psw2.borderStyle = UITextBorderStyleNone;
    self.psw2.layer.cornerRadius = AdaptedWidth(10);
    self.psw2.backgroundColor = UIColorHex(#F7F7F7);
    self.psw2.placeholder = XLocalized(@"请再次输入您的密码");;
    self.psw2.font = kDefaultFont(14);
    self.psw2.delegate = self;
    UIView*letfV1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.psw2.leftView = letfV1;
    self.psw2.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.psw2];
    [self.psw2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psw1.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    
    UILabel *tipLab3 = [UILabel new];
    tipLab3.font = kBoldFont(16);
    tipLab3.textColor = UIColorHex(333333);
    tipLab3.text = XLocalized(@"设置密码提示（非必填项）");
    [self.contentView addSubview:tipLab3];
    [tipLab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psw2.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    
    self.pswTip = [UITextField new];
    self.pswTip.borderStyle = UITextBorderStyleNone;
    self.pswTip.layer.cornerRadius = AdaptedWidth(10);
    self.pswTip.backgroundColor = UIColorHex(#F7F7F7);
    self.pswTip.placeholder = XLocalized(@"请输入您的密码提示");;
    self.pswTip.font = kDefaultFont(14);
    UIView*letfV2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.pswTip.leftView = letfV2;
    self.pswTip.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.pswTip];
    [self.pswTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLab3.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    
    UILabel *tipLab4 = [UILabel new];
    tipLab4.font = kBoldFont(16);
    tipLab4.textColor = UIColorHex(333333);
    tipLab4.text = XLocalized(@"请输入注册码");
    [self.contentView addSubview:tipLab4];
    [tipLab4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pswTip.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    
    UIButton *getBtn = [UIButton new];
    [getBtn setTitle:XLocalized(@"如何获取注册码？") forState:UIControlStateNormal];
    [getBtn setTitleColor:UIColorHex(#999999) forState:UIControlStateNormal];
    getBtn.titleLabel.font = kDefaultFont(13);
    [self.contentView addSubview:getBtn];
    [getBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kNormalSpace);
        make.centerY.equalTo(tipLab4.mas_centerY);
    }];
    kWeakSelf(self);
    [getBtn addTapBlock:^(UIButton * _Nonnull btn) {
//        [weakself.wallectService getTheInvitationCodeComplete:^{
//
//        }];
        [RegistrationCodeView show];
    }];
    
    self.pinvitationTF = [UITextField new];
    self.pinvitationTF.borderStyle = UITextBorderStyleNone;
    self.pinvitationTF.layer.cornerRadius = AdaptedWidth(10);
    self.pinvitationTF.backgroundColor = UIColorHex(#F7F7F7);
    self.pinvitationTF.placeholder = XLocalized(@"注册码");;
    self.pinvitationTF.font = kDefaultFont(14);
    UIView*letfV3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.pinvitationTF.leftView = letfV3;
    self.pinvitationTF.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.pinvitationTF];
    [self.pinvitationTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLab4.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    
    //    corner_nomal
    //    corner_select
    UIButton *btn = [UIButton new];
    [btn setImage:IMAGE_NAMED(@"corner_nomal") forState:UIControlStateNormal];
    [btn setImage:IMAGE_NAMED(@"corner_select") forState:UIControlStateSelected];
    [self.contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pinvitationTF.mas_bottom).offset(AdaptedWidth(5));
        make.left.mas_equalTo(AdaptedWidth(10));
        make.size.mas_equalTo(CGSizeMake(AdaptedWidth(35), AdaptedWidth(35)));
    }];    
    [btn addTapBlock:^(UIButton * _Nonnull btn) {
        btn.selected = !btn.selected;
        weakself.agree = !weakself.agree;
        [weakself importBtnEnable];
    }];
    YYLabel *agreementLab = [YYLabel new];
    NSString *read = XLocalized(@"我已仔细阅读并同意");
    NSString *terms = XLocalized(@"《服务协议》");
    NSString *or = XLocalized(@"及");
    NSString *terms1 = XLocalized(@"《隐私协议》");
    
    NSString *str =[NSString stringWithFormat:@"%@%@%@%@",read,terms,or,terms1];
    NSRange hightRange = [str rangeOfString:terms];
    NSMutableAttributedString *text  = [[NSMutableAttributedString alloc] initWithString:str];
    text.font = kDefaultFont(12);
    text.color = UIColorHex(333333);
    [text setUnderlineStyle:NSUnderlineStyleSingle range:hightRange];
    [text setTextHighlightRange:hightRange color:kColorMain backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebInfoViewController *vc = [WebInfoViewController new];
        vc.gotoURL =  @"https://htm.beesgame.io/#/serve";
        vc.title =  XLocalized(@"服务协议");
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    
    
    NSRange hightRange1 = [str rangeOfString:terms1];
    [text setUnderlineStyle:NSUnderlineStyleSingle range:hightRange1];
    [text setTextHighlightRange:hightRange1 color:kColorMain backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebInfoViewController *vc = [WebInfoViewController new];
        vc.gotoURL =  @"https://htm.beesgame.io/#/privacy";
        vc.title =  XLocalized(@"隐私协议");
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    agreementLab.attributedText = text;
    
    [self.contentView addSubview:agreementLab];
    [agreementLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btn.mas_centerY);
        make.left.equalTo(btn.mas_right);
        make.right.mas_equalTo(kNormalSpace);
    }];
    
    XThemeFlatButton*importBtn = [XThemeFlatButton button];
    self.improtBtn = importBtn;
    [importBtn setTitle:XLocalized(@"创建钱包") forState:UIControlStateNormal];
    [self.contentView addSubview:importBtn];
    [importBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn.mas_bottom).offset(AdaptedWidth(35));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(40));
        make.bottom.mas_equalTo(AdaptedWidth(-40));
    }];

    self.improtBtn.enabled = NO;
    self.psw1.delegate = self;
    self.psw2.delegate = self;
    [self.psw1 addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self.psw2 addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self.accountTF addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self.pinvitationTF addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
}
- (void)importBtnEnable{
    self.improtBtn.enabled = self.psw1.text.length && self.psw2.text.length && self.agree && self.pinvitationTF.text.length;
}

#pragma mark - textField
- (void)textChange:(UITextField*)textField{
    if (textField == self.accountTF && self.accountTF.text.length == 12) {
        self.wallectService.accountName = self.accountTF.text;
        [MBProgressHUD showLoadTitile:@"" ToView:self.view];
        [self.wallectService validAccountComplete:^(BOOL result, NSString * _Nonnull errorMsg) {
            [MBProgressHUD hideHUDForView:self.view];
            if (!result) {
                [self.view makeToast:errorMsg duration:2 position:CSToastPositionTop];
            }
        }];
    }
    [self importBtnEnable];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return [RegularExp controllABC123WithString:textField.text inRange:range inputString:string];
}

- (WallectService*)wallectService{
    if (!_wallectService) {
        _wallectService = [WallectService new];
    }
    return _wallectService;
}
@end
